package com.android.pagemarket.ui.activity.main;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.pagemarket.MyApplication;
import com.android.pagemarket.R;
import com.android.pagemarket.business.logic.ContentManager;
import com.android.pagemarket.business.update.UpdateManager;
import com.android.pagemarket.business.update.UpdateManager.CHECK_RESULT;
import com.android.pagemarket.business.update.UpdateManager.OnUpdateListener;
import com.android.pagemarket.business.update.UpdateManager.UpdateInfo;
import com.android.pagemarket.ui.activity.base.TabActivity;
import com.android.pagemarket.ui.activity.setting.AboutActivity;
import com.android.pagemarket.ui.activity.trend.TrandActivity;
import com.android.pagemarket.ui.widget.IndexTabView;
import com.android.pagemarket.ui.widget.TabIndexView;
import com.android.pagemarket.ui.widget.VideoPopWindow;
import com.android.pagemarket.util.NotifyListener;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-10-29
 * @see : 主界面
 * @Copyright : copyrights reserved by personal 2007-2011
 *********************************************************/
public class MainIndexActivity extends TabActivity
{
    private static final String TAG = "MainIndexActivity";
    public static final String ACTION_MSG_IN = "android.intent.action.MSG_IN";
    public static boolean isBackable;
    ///////////////////////////////////////////////////////////////////////
    private TabIndexView tabViews;
    private LAYOUT_TYPE  layoutType = LAYOUT_TYPE.DEFINE;
    private int mReqTab = -1;
    public static final int TAB_MAIN  = 1;
    public static final int TAB_TRAND = 2;
    public static final int TAB_ABOUT = 3;
    
    private VideoPopWindow videoPop;
    private Button pass_video;
    private SurfaceView surfaceView;
    ///////////////////////////////////////////////////////////////////////
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
        ContentManager.getInstance().setUnreadHandler(mHander);
        handIntent(getIntent());
        if(MyApplication.getContext().isFirst)
        {
            // 第一次进入            
            showWelcomeView();
        }else
        {
            // 以进入
            showMainView();
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent)
    {
        Log.d(TAG, "-->onNewIntent");
        super.onNewIntent(intent);
        handIntent(intent);
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        doReqTab();
        checkShortCut();
    }

    @Override
    protected void onPause()
    {        
        if(videoPop != null)
        {
            videoPop.pause();
            goMain();
        }
        hideDialog();
        super.onPause();
    }
    
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }
       
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
    }
    
    public void showFoucsPopWindow()
    {
        /**
        if(getPopupWin() == null)
        {
            setPopWin( new FoucsPopWindow(this));
        }
        try {
            getPopupWin().showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
//        DialogShowActivity.startActivity(this, DialogShowActivity.DIALOG_FOCUS, null);
        }catch(Exception e)
        {
            e.printStackTrace();
        }*/
        RegisterActivity.startActivity(this);
    }
    
    @Override
    public void onBackPressed()
    {      
        showDialog(true, getString(R.string.shortcut_notify), getString(R.string.tip_exit_app),
                   null, getString(R.string.cancel), new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        hideDialog();
                    }
                }, 
                   getString(R.string.sure), new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        hideDialog();
                        exit();
                    }
                });
    }
     
    @Override
    protected LAYOUT_TYPE getLayoutType()
    {
        return layoutType;
    }

    @Override
    protected void setupTabView(LinearLayout tabIndexLay)
    {
        // 设置自定义的tabView
        View tabs = inflate(R.layout.view_mian_tabs);                
        tabIndexLay.addView(tabs, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        
        IndexTabView trand_tab = getViewById(R.id.trand_tab);        
        IndexTabView main_tab = getViewById(R.id.main_tab);
        IndexTabView about_tab = getViewById(R.id.about_tab);
        
        int color1 = getResources().getColor(R.color.tab_normal_color);
        int color2 = getResources().getColor(R.color.tab_selected_color);
        
        trand_tab.setBackgroundResource(R.drawable.transparent_bg,R.drawable.bg_selected);
        trand_tab.setImageResource(R.drawable.ic_trand_unselected, R.drawable.ic_trand_selected);
        trand_tab.setText(R.string.tab_trand, color1, color2);
        
        main_tab.setBackgroundResource(R.drawable.transparent_bg,R.drawable.bg_selected);
        main_tab.setImageResource(R.drawable.ic_main_unselected, R.drawable.ic_main_selected);
        main_tab.setText(R.string.tab_main,  color1, color2);
        
        about_tab.setBackgroundResource(R.drawable.transparent_bg,R.drawable.bg_selected);
        about_tab.setImageResource(R.drawable.ic_about_unselected, R.drawable.ic_about_selected);
        about_tab.setText(R.string.tab_about, color1, color2);
        
        tabViews  = new TabIndexView();
        tabViews.setOnTabChangedListener(this);
        
        tabViews.addTab(TAB_TRAND, trand_tab, new Intent(this, TrandActivity.class));
        tabViews.addTab(TAB_MAIN, main_tab,  new Intent(this, MainActivity.class));
        tabViews.addTab(TAB_ABOUT, about_tab, new Intent(this, AboutActivity.class));
    }
    
    private void doReqTab()
    {
        if(tabViews != null)
        {
            if(mReqTab != -1)
            {
                tabViews.showTab(mReqTab);
                mReqTab = -1;
            }
        }
    }
    
    private void showWelcomeView()
    {        
        getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcome);
        
        final ImageView start_img = (ImageView)findViewById(R.id.start_img);
        pass_video = (Button)findViewById(R.id.pass_video); 
        surfaceView =(SurfaceView)findViewById(R.id.video_surface);
        
        pass_video.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                if(MyApplication.getContext().isShowVideo())
                {
                    OnClickListener listner = new OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            goMain();
                        }
                    };
                    videoPop = new VideoPopWindow(MainIndexActivity.this, listner);                   
                    start_img.setVisibility(View.GONE);
                    surfaceView.setVisibility(View.VISIBLE);
                    pass_video.setVisibility(View.VISIBLE);
                    surfaceView.requestFocus();
                    pass_video.setOnClickListener(listner);
                }else
                {
                    showMainView();
                }
            }
        }, 2000);        
    }
    
    private void goMain()
    {
        videoPop = null;
        MyApplication.getContext().addVideoCount();
        if(surfaceView != null) surfaceView.setVisibility(View.GONE);
        if(pass_video != null) pass_video.setVisibility(View.GONE);
        showMainView();
    }
    
    private void showMainView()
    {
        // 不是第一次进入，已显示主界面，返回
        if( !MyApplication.getContext().isFirst && mTabContentLayout != null)
        {          
            return;
        }        
        // 进入主界面
        layoutType = LAYOUT_TYPE.BOTTOM;
        MyApplication.getContext().isFirst = false;
        getLocalActivityManager().removeAllActivities();
        disableFullScreen();
        setContentView(R.layout.activity_tab_buttom);
        tabViews.showTab(mReqTab == -1 ? TAB_MAIN : mReqTab);
        mReqTab = -1;
        checkUpdate(null);
    }
    
    private void disableFullScreen()
    {
      WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
      localLayoutParams.flags = ( (~LayoutParams.FLAG_FULLSCREEN) & localLayoutParams.flags);
      getWindow().setAttributes(localLayoutParams);
      getWindow().clearFlags(LayoutParams.FLAG_LAYOUT_NO_LIMITS);
      getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, (~LayoutParams.FLAG_FULLSCREEN));
    }
    
    private void handIntent(Intent intent)
    {
        if(intent == null) return;
        String action = intent.getAction();
        if(action != null)
        {
            if(action.equals(ACTION_MSG_IN))
            {
                mReqTab = TAB_TRAND;
            }
        }
    }
    
    private void exit()
    {
        finish();
        Process.killProcess(Process.myPid());
    }
    
    /**
    private void listenScreen()
    {
        final IntentFilter filter = new IntentFilter();  
        filter.addAction(Intent.ACTION_SCREEN_OFF);  
        filter.addAction(Intent.ACTION_SCREEN_ON);  
        registerReceiver(mBatInfoReceiver, filter);
    }
    
    private void unlistenScreen()
    {
        unregisterReceiver(mBatInfoReceiver);
    }
    
    private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() 
    {  
        @Override  
        public void onReceive(Context context, final Intent intent)
        {  
            final String action = intent.getAction();
           if(Intent.ACTION_SCREEN_ON.equals(action))
           {  
               if(videoPop != null)
               {
                   videoPop.resume();
               }
           }else
           if(Intent.ACTION_SCREEN_OFF.equals(action))
           {  
               if(videoPop != null)
               {
                   videoPop.pause();
               }
           }  
        }
    };*/
    
    public Handler mHander = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            Log.d("main", "-->receive msg");
            if(msg.what == 0x12345678)
            {
                IndexTabView trand_tab = getViewById(R.id.trand_tab);
                if(trand_tab != null)
                {
                    trand_tab.setUnreadNum(msg.arg1);
                }
            }
        }
    };
    /////////////////////////////////////////////////////////////////////////
    private Queue<Dialog> dialogs = new LinkedBlockingQueue<Dialog>();
    public void checkUpdate(final NotifyListener<Boolean> listener)
    {
        UpdateManager.getInstacnce(this).startCheck(new OnUpdateListener()
        {
            @Override
            public void onUpdate(CHECK_RESULT result, final UpdateInfo updateInfo)
            {               
                    if(updateInfo != null && 
                      (result == CHECK_RESULT.NEED || result == CHECK_RESULT.HAVE))
                    {
                        MyApplication.getContext().isLastVer = false;
                        if(listener != null)
                        {
                            listener.onSucceed(false);
                        }
                        
                        int layId = R.layout.dialog_update_tip;        
                        View dialogView = getLayoutInflater().inflate(layId, null);
                        TextView version_name = (TextView)dialogView.findViewById(R.id.version_name);
                        TextView time = (TextView)dialogView.findViewById(R.id.time);
                        TextView size = (TextView)dialogView.findViewById(R.id.size); 
                        TextView info = (TextView)dialogView.findViewById(R.id.info);                       
                        version_name.setText(updateInfo.versionName);
                        time.setText(updateInfo.time);
                        size.setText(updateInfo.size);
                        info.setText(updateInfo.desc);
                        
                        showDialog(true,"发现新版本", null, dialogView, 
                                result == CHECK_RESULT.NEED?null:"以后再说", null,
                                result == CHECK_RESULT.NEED?"确定":"立即更新",
                                new DialogInterface.OnClickListener() 
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) 
                                    {
                                        String saveDir = Environment.getExternalStorageDirectory().getAbsolutePath();
                                        saveDir += "/update/";
                                        UpdateManager.getInstacnce(MainIndexActivity.this)
                                            .startUpdateNotify(updateInfo.path, saveDir, 
                                             new Intent(MainIndexActivity.this, MainIndexActivity.class));
                                        dialog.dismiss();
                                    }
                                });
                    }else
                    if(result == CHECK_RESULT.NONE)
                    {
                        MyApplication.getContext().isLastVer = true;
                        if(listener != null)
                        {
                            listener.onSucceed(true);
                        }
                    }else
                    {
                        if(listener != null)
                        {
                            listener.onError(-1);
                        }
                    }
                }
        });
    }
    
    /** 显示自定义弹出窗体*/
    public Dialog showDialog(boolean isCenter, String title, String msg,View contentView,
            String cancelbtnName, DialogInterface.OnClickListener cancelbtnListener,
            String okbtnName,DialogInterface.OnClickListener okbtnListener)
    {
        // 在创建新的窗体
        Builder builder = new AlertDialog.Builder(this);
        if(title != null)
        {
            builder.setTitle(title);
        }
        if(msg != null)
        {
            builder.setMessage(msg);
        }
        if(cancelbtnName != null)
        {
            builder.setNegativeButton(cancelbtnName,cancelbtnListener);
        }
        if(okbtnName != null)
        {
            builder.setPositiveButton(okbtnName, okbtnListener);
        }
        if(contentView != null)
        {
            builder.setView(contentView);
        }
                
        Dialog dialog = builder.create();
        if(!isCenter)
        {
            Window mwindow=dialog.getWindow(); 
            mwindow.setGravity(Gravity.LEFT | Gravity.TOP);
            WindowManager.LayoutParams lp=mwindow.getAttributes(); 
            lp.x=20;
            lp.y=50;
            mwindow.setAttributes(lp);
        }
        addQueueDialog(dialog);
        return dialog;
    }
    
    /** 添加到窗口显示队列中 */
    private void addQueueDialog(Dialog dialog)
    {
        // 取消事件监听器
        dialog.setOnDismissListener(new OnDismissListener()
        {            
            @Override
            public void onDismiss(DialogInterface dialog)
            {
                dialogs.poll();
                showQueueDialog();
            }
        });
        dialogs.offer(dialog);
        showQueueDialog();
    }
    
    /** 显示队列中窗口 */
    private void showQueueDialog()
    {
        if(!dialogs.isEmpty())
        {
            if(!dialogs.peek().isShowing())
            {
                dialogs.peek().show();
            }
        }
    }
    
    /** 关闭自定义弹出窗体 */   
    private void hideDialog()
    {
        if(dialogs != null && dialogs.size() > 0)
        {
            if(!dialogs.isEmpty())
            {
                Dialog dialog = dialogs.peek();
                if(dialog.isShowing())
                {
                    dialog.dismiss();
                }
            }
        }
    }
    
    /** 添加快捷图标 */
    private void checkShortCut()
    {
        if(!MyApplication.getContext().isShowShortCut())
        {
            // 已存在
            return;
        }
        // 只提示一次
        MyApplication.getContext().isShortCutTip = true;
        MyApplication.getContext().setShortCut(true);
        // 显示窗口
        showDialog(true, getString(R.string.shortcut_notify), getString(R.string.shortcut_notify_text),
                  null, getString(R.string.cancel), null,
                  getString(R.string.sure), new DialogInterface.OnClickListener()
                 {
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
                        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                                getString(R.string.app_name));
                        // 是否可以有多个快捷方式的副本，参数如果是true就可以生成多个快捷方式，如果是false就不会重复添加
                        intent.putExtra("duplicate", false);

                        Intent intent2 = new Intent(Intent.ACTION_MAIN);
                        intent2.addCategory(Intent.CATEGORY_LAUNCHER);
                        // 删除的应用程序的ComponentName，即应用程序包名+activity的名字
                        intent2.setComponent(new ComponentName(
                                getPackageName(),MainIndexActivity.class.getName()));

                        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
                        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                                Intent.ShortcutIconResource.fromContext(
                                        MainIndexActivity.this,
                                        R.drawable.ic_launcher));
                        sendBroadcast(intent);
                        MyApplication.getContext().setShortCut(true);
                    }
                });
    }
}